package com.bear.fastrepair.mvvm.ui.employee.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.bear.fastrepair.MainActivity
import com.bear.fastrepair.R
import com.bear.fastrepair.base.BaseFragment
import com.bear.fastrepair.databinding.FragmentOrderDetailBinding
import com.bear.fastrepair.entity.*
import com.bear.fastrepair.mvvm.ui.employee.*
import com.bear.fastrepair.mvvm.ui.employee.adapter.OrderDetailAdapter
import com.bear.fastrepair.mvvm.ui.employee.dialog.BillCommitDialog
import com.bear.fastrepair.mvvm.ui.employee.dialog.BillDetailDialog
import com.bear.fastrepair.mvvm.ui.employee.dialog.CommonDialog
import com.bear.fastrepair.utils.*
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.github.gzuliyujiang.wheelpicker.DatimePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.annotation.TimeMode
import com.github.gzuliyujiang.wheelpicker.entity.DatimeEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class OrderDetailFragment : BaseFragment<FragmentOrderDetailBinding>() {
    private lateinit var globalViewModel: EmployeeViewModel
    private lateinit var privateViewModel: EmployeeViewModel

    // 详情数据源
    private val dataList = ArrayList<ItemType>()
    override val title: String
        get() = "订单详情"

    @SuppressLint("NotifyDataSetChanged")
    override fun init() {
        val main = requireActivity() as MainActivity
        binding.toolbar.toolbarTitle.text = title
        globalViewModel = ViewModelProvider(
            requireActivity(),
            EmployeeViewModelFactory()
        ).get(EmployeeViewModel::class.java)
        privateViewModel = ViewModelProvider(
            this,
            EmployeeViewModelFactory()
        ).get(EmployeeViewModel::class.java)
        val record = arguments?.getString("record")

        var serviceOrderId = record ?: return
        val personalInfo = globalViewModel.personalInfo.value ?: return

        main.setNewOrderListener {
            serviceOrderId = it
            privateViewModel.getOrderById(serviceOrderId)
        }

        privateViewModel.getOrderById(serviceOrderId)
//        viewModel.getOrderInfoDetail.value?.code = -1

        val adapter = OrderDetailAdapter(dataList, privateViewModel, requireContext(), this, serviceOrderId, personalInfo)

//                val separator1 = SeparatorType("原始图片")
        val separator2 = SeparatorType("服务订单处理流程")
        val separator3 = SeparatorType("现场记录")

        // 无需全局ViewModel
        adapter.clickBillLog = {
            BillDetailDialog(requireContext(), this, privateViewModel, serviceOrderId).show()
        }
        // 无需全局ViewModel
        adapter.clickBillCommit = {
            BillCommitDialog(requireContext()) { bill ->
//                val list =
//                    globalViewModel.selectedImage.value?.map { uri -> UriUtils.uri2File(uri) }
//                if (list == null || list.isEmpty()) {
//                    bill.serviceOrderId = serviceOrderId
//                    globalViewModel.addOrderBill(bill)
//                } else {
//                    globalViewModel.imageUpload(params = list)
//                    globalViewModel.billInfo.value = bill
//                }
                bill.serviceOrderId = serviceOrderId
                privateViewModel.addOrderBill(bill)
            }.show()
        }
        // 无需全局ViewModel
        adapter.clickBooking = { block ->
            val picker = DatimePicker(requireActivity())
            val wheelLayout = picker.wheelLayout
            picker.setTitle("设置预约开始时间")
            picker.setOnDatimePickedListener { year, month, day, hour, minute, _ ->
                val text =
                    "$year-${if (month < 10) "0$month" else month}-${if (day < 10) "0$day" else day} ${if (hour < 10) "0$hour" else hour}:${if (minute < 10) "0$minute" else minute}"
                val picker1 = DatimePicker(requireActivity())
                val wheelLayout1 = picker1.wheelLayout
                picker1.setTitle("设置预约结束时间")
                picker1.setOnDatimePickedListener setOnDatimePickedListener1@{ year1, month1, day1, hour1, minute1, _ ->
                    val text1 =
                        "$year1-${if (month1 < 10) "0$month1" else month1}-${if (day1 < 10) "0$day1" else day1} ${if (hour1 < 10) "0$hour1" else hour1}:${if (minute1 < 10) "0$minute1" else minute1}"
//                            if (!(year1 > year && month1 > month && day1 > day && hour1 > hour && minute1 > minute)) {
//                                ToastUtils.showLong("预约结束时间不允许比开始时间早哦")
//                                return@setOnDatimePickedListener1
//                            }
                    block(arrayOf(text, text1))
                }
                wheelLayout1.setDateMode(DateMode.YEAR_MONTH_DAY)
                wheelLayout1.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                wheelLayout1.setRange(DatimeEntity.now(), DatimeEntity.yearOnFuture(10))
                wheelLayout1.setDateLabel("年", "月", "日")
                wheelLayout1.setTimeLabel("时", "分", "秒")
                picker1.show()
            }
            wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
            wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
            wheelLayout.setRange(DatimeEntity.now(), DatimeEntity.yearOnFuture(10))
            wheelLayout.setDateLabel("年", "月", "日")
            wheelLayout.setTimeLabel("时", "分", "秒")
            picker.show()
        }
        binding.rvDetail.let {
            it.layoutManager = LinearLayoutManager(requireContext())
            it.adapter = adapter
        }
        privateViewModel.getOrderInfoDetail.observe(viewLifecycleOwner) {
            if (it.code == 0) {
                dataList.clear()
                val detailType = DetailDataType(it.data)
                val logTypes = it.data.orderLogList.map { log -> OrderLogType(log) }
                privateViewModel.orderStatusUpdate(it.data.serviceOrderStatus)
                val uploadImagesType =
                    UploadImagesType(arrayListOf(BitmapInfo(resId = R.drawable.add_img)))
                val networkImages =
                    it.data.orderImages.split(",").filter { url -> url.isNotEmpty() }
                        .map { url -> BitmapInfo(url = url) }
                val networkImagesList = ArrayList<BitmapInfo>().apply {
                    addAll(networkImages)
                }
                val imagesType = ImagesType(networkImagesList, it.data)
                dataList.add(detailType)
//                if (networkImages.isNotEmpty()) dataList.add(separator1)
                dataList.add(imagesType)
                if (logTypes.isNotEmpty()) dataList.add(separator2)
                dataList.addAll(logTypes)
                adapter.notifyDataSetChanged()
                privateViewModel.getImagesById(serviceOrderId)
            }
        }

        privateViewModel.orderImages.observe(viewLifecycleOwner) { oi ->
            val index = dataList.indexOf(separator3)
            if (index != -1) {
                dataList.remove(separator3)
                dataList.removeAll{ it is OrderImagesType }
            }

            val orderImagesType = oi.data.map { data -> OrderImagesType(data) }
            if (orderImagesType.isNotEmpty()) dataList.add(separator3)
            dataList.addAll(orderImagesType)
            adapter.notifyDataSetChanged()
        }

        privateViewModel.serviceOrderStatus.observe(viewLifecycleOwner) {
            observeBtn(it)
        }

        privateViewModel.saveBookingTime.observe(viewLifecycleOwner) {
            if (it.code == 0) {
                ToastUtils.showLong("预约时间设置成功")
                privateViewModel.getOrderById(serviceOrderId)
//                privateViewModel.bookingTime.value = null
            } else if (it.code != -1) {
                ToastUtils.showLong("预约时间设置失败，请重新设置")
            }
//            viewModel.saveBookingTime.value?.code = -1
        }

        // 预留的内容，账单带图片暂不需支持
//        globalViewModel.imageUploadBill.observe(viewLifecycleOwner) {
//            if (it.code == 0) {
//                globalViewModel.billInfo.value?.let { bill ->
//                    bill.serviceOrderId = serviceOrderId
//                    globalViewModel.addOrderBill(bill)
//                    globalViewModel.billInfo.value = null
//                }
//            }
//            globalViewModel.imageUploadBill.value?.code = -1
//        }

        // 图片上传后的livedata变化
        privateViewModel.orderImageUpload.observe(viewLifecycleOwner) {
//            globalViewModel.addImages(emptyList())
            if (it.responseListInfo.code == 0) {
                when (it.status) {
                    ORDER_COMPLETE -> globalViewModel.orderComplete(serviceOrderId, remark = it.remarks)
                    ORDER_SEND_BACK -> globalViewModel.orderBack(serviceOrderId, remark = it.remarks)
                    MACHINE_TAKE_BACK -> globalViewModel.takeMachineBack(
                        serviceOrderId,
                        remark = it.remarks
                    )
                    TAKE_BACK_REPAIRED -> globalViewModel.takeMachineBackRepaired(
                        serviceOrderId,
                        remark = it.remarks
                    )
                    // 只有这里会走，因为状态变化上传图片这个需求不需要去掉了。
                    // 这里是图片上传成功后通过使用返回的url发起上传图片项目的请求
                    IMAGE_UPLOAD -> {
                        var imagesInfo = ""
                        val data = it.responseListInfo.data
                        data.forEachIndexed { index, url ->
                            imagesInfo += if (data.lastIndex == index) {
                                url
                            } else {
                                "${url},"
                            }
                        }
                        privateViewModel.uploadImages(
                            EmployeeUploadImage(
                                it.remarks,
                                imagesInfo,
                                serviceOrderId
                            )
                        )
                    }
                }
//                globalViewModel.getOrderById(serviceOrderId)
//                it.responseListInfo.code = -1
            }
        }
        binding.clockIn.setOnClickListener {
            privateViewModel.launch {
                withContext(Dispatchers.IO) {
                    LocationHelper.getLocationInfo(requireContext()) {
                        it ?: run {
                            ToastUtils.showLong("定位信息获取失败，请检查定位权限并重试")
                            return@getLocationInfo
                        }
                        privateViewModel.employeeClockIn(
                            it.address,
                            locationLatitude = "${it.latitude}",
                            locationLongitude = "${it.longitude}",
                            serviceOrderId
                        )
                    }
                }
            }
        }
        binding.orderComplete.setOnClickListener {
            CommonDialog(requireContext(), "确认完成订单") {
//                val list = globalViewModel.selectedImage.value?.map { uri -> UriUtils.uri2File(uri) }
//                if (list == null || list.isEmpty()) {
//                    globalViewModel.orderComplete(serviceOrderId, remark = it)
//                } else {
//                    globalViewModel.imageUploadOrder(params = list, status = ORDER_COMPLETE, remark = it)
//                }
                privateViewModel.orderComplete(serviceOrderId, remark = it)
            }.show()
        }
        binding.orderBack.setOnClickListener {
            CommonDialog(requireContext(), "确认退回订单") {
//                val list = globalViewModel.selectedImage.value?.map { uri -> UriUtils.uri2File(uri) }
//                if (list == null || list.isEmpty()) {
//                    globalViewModel.orderBack(serviceOrderId, remark = it)
//                } else {
//                    globalViewModel.imageUploadOrder(params = list, status = ORDER_SEND_BACK, remark = it)
//                }
                privateViewModel.orderBack(serviceOrderId, remark = it)
            }.show()
        }
        binding.machineBack.setOnClickListener {
            CommonDialog(requireContext(), "确认带回机器") {
//                val list = globalViewModel.selectedImage.value?.map { uri -> UriUtils.uri2File(uri) }
//                if (list == null || list.isEmpty()) {
//                    globalViewModel.takeMachineBack(serviceOrderId, remark = it)
//                } else {
//                    globalViewModel.imageUploadOrder(
//                        params = list,
//                        status = MACHINE_TAKE_BACK,
//                        remark = it
//                    )
//                }
                privateViewModel.takeMachineBack(serviceOrderId, remark = it)
            }.show()
        }
        binding.backRepaired.setOnClickListener {
            CommonDialog(requireContext(), "确认带回维修完成") {
//                val list = globalViewModel.selectedImage.value?.map { uri -> UriUtils.uri2File(uri) }
//                if (list == null || list.isEmpty()) {
//                    globalViewModel.takeMachineBackRepaired(serviceOrderId, remark = it)
//                } else {
//                    globalViewModel.imageUploadOrder(
//                        params = list,
//                        status = TAKE_BACK_REPAIRED,
//                        remark = it
//                    )
//                }
                privateViewModel.takeMachineBackRepaired(serviceOrderId, remark = it)
            }.show()
        }

//        binding.billCommit.setOnClickListener {
//            BillCommitDialog(requireContext()) { bill ->
//                val list = globalViewModel.selectedImage.value?.map { uri -> UriUtils.uri2File(uri) }
//                if (list == null || list.isEmpty()) {
//                    bill.serviceOrderId = serviceOrderId
//                    globalViewModel.addOrderBill(bill)
//                } else {
//                    globalViewModel.imageUpload(params = list)
//                    globalViewModel.billInfo.value = bill
//                }
//            }.show()
//        }

        binding.imageUpload.setOnClickListener {
            UploadImageDialog(
                requireContext(),
                arrayListOf(BitmapInfo(resId = R.drawable.add_img)),
                globalViewModel,
                this
            ) { remarks, files ->
//                val files = ArrayList<File>()
//                val list = viewModel.selectedImage.value?.map { uri -> UriUtils.uri2File(uri) }
//                val list2 = viewModel.captureImage.value
                if (files.isEmpty()) {
//                    viewModel.uploadImages(EmployeeUploadImage(it, "备注：无", serviceOrderId))
                    ToastUtils.showLong("请点击加号选择图片再上传")
                } else {
                    // 先上传图片到服务器
                    privateViewModel.imageUploadOrder(
                        params = files,
                        status = IMAGE_UPLOAD,
                        remark = remarks
                    )
                }
            }.show()
        }

//        binding.billLog.setOnClickListener {
//            BillDetailDialog(requireContext(), this, globalViewModel).show()
//        }
    }

    private fun observeBtn(status: Int?) {
        when (status) {
            // 已分派（待上门） -> 订单退回，打卡
            ORDER_PREPARE -> {
                binding.clockIn.visibility = View.VISIBLE
                binding.orderComplete.visibility = View.GONE
                binding.orderBack.visibility = View.VISIBLE
                binding.machineBack.visibility = View.GONE
                binding.backRepaired.visibility = View.GONE
                binding.imageUpload.visibility = View.GONE
            }
            // 已打卡 -> 订单退回，机器带回，完成订单
            CLOCK_IN -> {
                binding.clockIn.visibility = View.GONE
                binding.clockIn.isEnabled = false
                binding.orderComplete.visibility = View.VISIBLE
                binding.orderBack.visibility = View.VISIBLE
                binding.machineBack.visibility = View.VISIBLE
                binding.backRepaired.visibility = View.GONE
                binding.imageUpload.visibility = View.VISIBLE
            }
            // 已完成 -> 无
            ORDER_COMPLETE -> {
                binding.clockIn.visibility = View.GONE
                binding.orderComplete.visibility = View.GONE
                binding.orderComplete.isEnabled = false
                binding.orderBack.visibility = View.GONE
                binding.machineBack.visibility = View.GONE
                binding.backRepaired.visibility = View.GONE
                binding.imageUpload.visibility = View.GONE
            }
            // 订单退回 -> 无
            ORDER_SEND_BACK -> {
                binding.clockIn.visibility = View.GONE
                binding.orderComplete.visibility = View.GONE
                binding.orderBack.visibility = View.GONE
                binding.orderBack.isEnabled = false
                binding.machineBack.visibility = View.GONE
                binding.backRepaired.visibility = View.GONE
                binding.billCommit.visibility = View.GONE
                binding.imageUpload.visibility = View.GONE
            }
            // 机器带回 -> 订单退回，维修完成
            MACHINE_TAKE_BACK -> {
                binding.clockIn.visibility = View.GONE
                binding.orderComplete.visibility = View.GONE
                binding.orderBack.visibility = View.VISIBLE
                binding.machineBack.visibility = View.GONE
                binding.machineBack.isEnabled = false
                binding.backRepaired.visibility = View.VISIBLE
                binding.imageUpload.visibility = View.VISIBLE
            }
            // 维修完成
            TAKE_BACK_REPAIRED -> {
                binding.clockIn.visibility = View.GONE
                binding.orderComplete.visibility = View.GONE
                binding.orderBack.visibility = View.GONE
                binding.machineBack.visibility = View.GONE
                binding.backRepaired.visibility = View.GONE
                binding.backRepaired.isEnabled = false
                binding.billCommit.visibility = View.GONE
                binding.imageUpload.visibility = View.GONE
            }
        }
    }
}